<template>
  <div class="login">
    <el-row>
      <el-col :span="10" :offset="7">
        <div class="login-div">
          <p class="title">小U商城后台管理系统</p>
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="用户名" prop="username">
              <el-input class="login-input" v-model="ruleForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input class="login-input" v-model="ruleForm.password"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm('ruleForm')"
                >立即登录</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 表单中的数据
      ruleForm: {
        username: 'admin',
        password: 'admin888'
      },
      // 定义表单检验的规则
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password:[
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 点击登录按钮，需要先校验表单
    submitForm(formName) {
      // this.$refs这是查找dom元素，找到表单，然后才能校验
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 去登录
          this.login();
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 真的去登录了
    login() {
      this.$axios.post('/userlogin', {
        username: this.ruleForm.username,
        password: this.ruleForm.password
      })
        .then(res => {
          console.log(res.data.list.token);
          if(res.data.code === 200) {
            // 登录成功，记录信息
            this.$store.commit('setUserInfo', res.data.list)
          }
          this.$router.push('/index')
        })
        .catch(err => {
          console.log(err);
        })
    }
  },
};
</script>
<style lang="">
.login {
  width: 100vw;
  height: 100vh;
  background-image: url("../assets/login-bg.jpeg");
}
.login-div {
  margin-top: 200px;
  height: 300px;
  background-color: #fff;
  border-radius: 10px;
}
.title {
  text-align: center;
  font-weight: 600;
  line-height: 3;
  font-size: 20px;
}
.login-input {
  width: 280px;
}
</style>